package com.jsgt.greekfire.dao.viewmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.jsgt.greekfire.common.containsIgnoreCase
import com.jsgt.greekfire.common.http.safeLaunch
import com.jsgt.greekfire.dao.AppDatabase
import com.jsgt.greekfire.dao.dao.MarketBeanDao
import com.jsgt.greekfire.dao.model.MarketBean
import com.jsgt.greekfire.dao.model.NetLoadResult
import com.jsgt.greekfire.repository.CoinRepository

class MarketBeanViewModel(application: Application, private val inArray: Array<String?>) :
    AndroidViewModel(application) {
    private var userDao: MarketBeanDao? = null
    private val coinRepository = CoinRepository.instance

    init {
        userDao = AppDatabase.getInstance(application).marketBeanDao()
    }

    val marketListLiveData by lazy { userDao?.getAll(inArray) }
    val netLoadLiveData by lazy { MutableLiveData<NetLoadResult>() }

    /**
     * 行情列表
     */
    fun getMarketList() {
        viewModelScope.safeLaunch {
            block = {
                val data = coinRepository.getMarketList()
                if (data.code == 0) {
                    if (data.data != null) {
                        data.data.forEach {
                            it.sort = inArray.indexOf(it.symbol)
                        }
                        userDao?.addMarketBean(data.data)
                        netLoadLiveData.value = NetLoadResult(NetLoadResult.STATUS_SUCCESS, null)
                    } else {
                        netLoadLiveData.value = NetLoadResult(NetLoadResult.STATUS_FAILED, data.msg)
                    }
                } else {
                    netLoadLiveData.value = NetLoadResult(NetLoadResult.STATUS_FAILED, data.msg)
                }
            }
            onError = {
                netLoadLiveData.value = NetLoadResult(NetLoadResult.STATUS_FAILED, it.message)
            }
        }
    }


}